package com.cn.tool;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.*;
import com.cn.Object.Person;

import java.util.*;

/**
 * @author he_ls
 * @since 2024/6/26 17:59
 **/
public class JsonTest {
    public static void main(String[] args) {
        ArrayList<String> toysB = CollectionUtil.newArrayList("霸天虎", "汽车人", "天罡变");
        ArrayList<String> toysG = CollectionUtil.newArrayList("洋娃娃", "汽车人", "小马驹");
        Person p = new Person("小明", 12, "男", "深圳市", new Date(1324234215435L), toysB);
        Person pNull = new Person("小红", null, "女", null, new Date(1124234215435L), toysG);
        Person[] pArray = {p, pNull};
        //
        test3(pArray);
    }

    static void test4() {

    }

    static void test3(Person[] pArray) {
        JSON json = JSONUtil.parse(pArray);
        System.out.println(json);
        Person[] bean = json.toBean(Person[].class);
        JSONObject jsonObject = JSONUtil.parseObj(bean[0]);
        // jsonObject的value是json对象也可以直接获得
        JSONArray toyList = jsonObject.getJSONArray("toyList");

        JSONArray jsonArray = JSONUtil.parseArray(pArray);
//        System.out.println(jsonArray);
        List<Person> list = jsonArray.toList(Person.class);
        System.out.println("list : " + list);
        HashMap<String, String> map = new HashMap<>();
        map.put("name", "小张");
        jsonArray.add(map);
        System.out.println(jsonArray);
        System.out.println(jsonArray.getByPath("name"));
        System.out.println(jsonArray.toStringPretty());

    }

    static void test2(Person p) {
        JSONObject jsonObject = JSONUtil.parseObj(p, false);
        jsonObject.setDateFormat("yyyy-MM-dd hh:mm:ss");

        System.out.println("jsonObjectString: " + jsonObject.toString());
        Person bean = jsonObject.toBean(Person.class);
        System.out.println(bean);

        JSONObject js = JSONUtil.parseObj(jsonObject.toStringPretty());
        System.out.println("js : " + js);
    }

    static void test1(Person person) {
        JSONConfig jsonConfig = new JSONConfig();
        jsonConfig.setIgnoreError(false).setIgnoreNullValue(false);
        JSON json = JSONUtil.parse(person, jsonConfig);
        System.out.println("json : " + json.toBean(Person.class));
        System.out.println(json.getByPath("age"));
        System.out.println("jsonPretty : " + json.toStringPretty());
        JSONObject jsonObject = JSONUtil.parseObj(json);
    }

}
